package com.wanban.download.runnable

import android.util.Log
import com.wanban.download.Params
import com.wanban.download.utils.PathUtils
import com.wanban.download.WBDownloadUtils
import com.wanban.download.base.BaseDownloadInterface
import com.wanban.download.listener.OnFileDownloadListener
import com.wanban.download.utils.DownloadConstants
import com.wanban.download.utils.NetworkUtils
import java.util.concurrent.ThreadPoolExecutor

class MultipleThreadDownloadSingleFileUtils(
    private val url: String,
    private val rootFilePath: String?,
    private val listener: OnFileDownloadListener?,
    private val header: Map<String, String>? = null,
): BaseDownloadInterface(false) {

    @Volatile
    private var retryTime = 0
    // 当前文件大小
    private var totalLength = 0L
    // 多线程的数量
    private var threadNumber = Params.DEFAULT_DOWNLOAD_THREAD_NUMBER

    override fun startDownload(totalLength: Long) {
        if (totalLength <= 0L) {
            listener?.onError(url, DownloadConstants.ERROR_FILE_LENGTH)
            return
        }
        this.totalLength = totalLength
        // 已经获取到长度，直接分配线程下载即可
        val size = totalLength / threadNumber
        for (i in 0 until threadNumber) {
            // 1.确定每个线程的下载区间
            // 2.开启对应的子线程
            val startPosition = i * size //开始位置
            var endPosition = (i + 1) * size - 1 //结束位置
            // 最后一个线程
            if (i == threadNumber - 1) {
                endPosition = totalLength - 1
            }
            Log.e(WBDownloadUtils.TAG, "startPosition: $startPosition - endPosition:$endPosition")
            val mp4FiePath = PathUtils.getMp4File(rootFilePath)
            if (mp4FiePath == null) {
                listener?.onError(url, DownloadConstants.ERROR_DOWNLOAD_FILE_CREATE)
                return
            }
            val downloadFileUtils = SingleThreadDownloadSingleFileUtils(url, mp4FiePath.absolutePath, object: OnFileDownloadListener {
                override fun onStart(url: String) {}

                override fun onProgress(url: String, speed: Long, currentLength: Long, percent: Float) {
                    currentDownloadSpeed += speed
                    currentDownloadLength += speed
                }

                override fun onError(url: String, errorMsg: String) {
                    if (isInterrupted) return
                    if (retryTime < Params.MIN_DOWNLOAD_RETRY_TIMES) {
                        retryTime++
                        // 重启下载
                        if (isInterrupted) return
                        if (!NetworkUtils.isConnected()) {
                            retryTime = 0
                            cancel()
                            listener?.onError(url, errorMsg)
                            return
                        }
                        startDownload(totalLength)
                    } else {
                        retryTime = 0
                        if (isInterrupted) return
                        cancel()
                        listener?.onError(url, errorMsg)
                    }
                }

                override fun onComplete(url: String, length: Long, path: String?) {
                    if ((executors as ThreadPoolExecutor).queue.isNullOrEmpty()) {  // 全部完成
                        if (isInterrupted) return
                        cancel()
                        listener?.onComplete(url, totalLength, mp4FiePath.absolutePath)
                    }
                }

            }, header, startPosition, endPosition)

            if (executors.isTerminated || executors.isShutdown) {
                isInterrupted = true
                return
            }
            executors.submit(downloadFileUtils.getDownloadRunnable())
            startProgressCallback()
        }
    }

    override fun onProgressCallback() {
        if (isInterrupted) return
        val percent = currentDownloadLength * 1f / totalLength
        listener?.onProgress(url, currentDownloadSpeed, currentDownloadLength, percent)
        currentDownloadSpeed = 0
        currentDownloadLength = 0
    }

}

